package com.kehutong.charge.service.impl;

import com.kehutong.charge.entity.*;
import com.kehutong.charge.util.CommonUtil;
import com.kehutong.charge.util.enums.ChargeBillStatusEnum;
import com.kehutong.charge.util.enums.FeeStatusEnum;
import com.kehutong.charge.vo.ChargeFeeManageExcelVO;
import com.kehutong.charge.service.ChargeFeeApplyService;
import com.kehutong.charge.service.CommonService;
import com.kehutong.charge.util.enums.ChargeLogEnum;
import com.kehutong.charge.util.enums.ChargeStatusEnum;
import com.kehutong.common.errcode.Assert;
import com.kehutong.common.errcode.Result;
import com.kehutong.common.excel.tool.ExcelTool;
import com.kehutong.common.util.ListUtils;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.execute.entity.FindPage;
import org.coraframework.util.EnumUtil;
import org.coraframework.util.Objects;
import org.coraframework.util.time.TimeUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;

/**
 * @program: kht
 * @description: 费用申请业务
 * @author: jian Ye
 * @create: 2021/8/4
 **/
public class ChargeFeeApplyServiceImpl implements ChargeFeeApplyService {

    @Inject
    private JdbcSession jdbcSession;
    @Inject
    CommonService commonService;
    @Inject
    private ExcelTool excelTool;

    @Override
    public Page<ChargeFeeManage> findPage(JSONObject jsonObject) {
        FindPage<ChargeFeeManage> find = jdbcSession.findPage(ChargeFeeManage.class)
                .eq("deleted", false)
                .eq(jsonObject,"communityNo")
                .eq(jsonObject,"applyStatus")
                .like(jsonObject,"createTime");
        String serviceNo = jsonObject.getString("serviceNo");
        if(Objects.nonEmpty(serviceNo)){
            find.markBegin();
            find.like("serviceNo",serviceNo).or();
            find.like("orderNo",serviceNo).or();
            find.markEnd();
        }
        //添加选中导出条件
        JSONArray exportIdList = jsonObject.getJSONArray("exportIdList");
        if(!Objects.isEmpty(exportIdList)){
            find.in("serviceNo",exportIdList);
        }
        find.order("createTime", "desc");

        return find.page(jsonObject).exe();
    }


    @Override
    public void pageExport(HttpServletRequest req, HttpServletResponse resp, JSONObject jsonObject) {
        jsonObject.put("pageNo", 1);
        jsonObject.put("pageSize", Short.MAX_VALUE);
        List<ChargeFeeManage> list = findPage(jsonObject).getList();
        Assert.notEmpty(list,"导出失败！没有找到相关的费用申请数据");
        List<ChargeFeeManageExcelVO> dtoList = ListUtils.copyList(list, ChargeFeeManageExcelVO::new);
        excelTool.excelDownload(req,resp,dtoList,"费用申请列表导出");
    }


    @Override
    public List<ChargeFeeManage> findList(JSONObject jsonObject) {

        return jdbcSession.findArray(ChargeFeeManage.class)
                .eq(jsonObject,"communityNo")
                .eq(jsonObject,"orderNo").exe();
    }


    @Override
    public Object save(ChargeFeeManage chargeFeeManage) throws Exception {

        return jdbcSession.insert(chargeFeeManage);
    }


    @Override
    public Object update(ChargeFeeManage chargeFeeManage) throws Exception {

        /**
         * 审核流程，修改账单金额
         */
        ChargeFeeManage feeManage = jdbcSession.findById(ChargeFeeManage.class,chargeFeeManage.getId());
        feeManage.setApplyStatus(chargeFeeManage.getApplyStatus());
        feeManage.setRemark(chargeFeeManage.getRemark());
        feeManage.setUpdateName(chargeFeeManage.getUpdateName());
        feeManage.setUpdateNo(chargeFeeManage.getUpdateNo());
        feeManage.setApplyTime(TimeUtil.timestamp());

        if(chargeFeeManage.getApplyStatus().getId().equals(FeeStatusEnum.CS_SUCCESS.getId())){

            //查询所有调整的费用
            List<ChargeFeeChange> feeChanges = jdbcSession.findArray(ChargeFeeChange.class)
                    .eq("serviceNo",feeManage.getServiceNo()).exe();

            String houseBillNo = null;
            for (int i = 0; i < feeChanges.size(); i++) {

                ChargeFeeChange feeChange = feeChanges.get(i);
                //修改账单数据
                ChargeBillItems billItems = jdbcSession.findOne(ChargeBillItems.class)
                        .eq("itemBillNo",feeChange.getChargeBillNo()).exe();
                //调整应付金额
                billItems.setPayableAmount(feeChange.getPayableAmount());
                jdbcSession.updateById(billItems);
                houseBillNo = billItems.getHouseBillNo();
            }

            ChargeBillHouse billHouse = jdbcSession.findOne(ChargeBillHouse.class)
                    .eq("houseBillNo",houseBillNo)
                    .exe();
            billHouse.setBillAmountUnPaid(feeManage.getPayableAmount());
            jdbcSession.updateById(billHouse);

            //审核成功则，需要修改账单金额
            ChargeBillItems billItems = jdbcSession.findOne(ChargeBillItems.class)
                    .eq("itemBillNo",feeManage.getOrderNo())
                    .eq("chargeStatus",ChargeBillStatusEnum.BILL_UN_PAID).exe();

            commonService.insetLogger(feeManage.getServiceNo(),
                    ChargeLogEnum.LOG_CHARGE_ORDER_APPLY.getDesc(),
                    "费用审核操作",
                    FeeStatusEnum.CS_SUCCESS.getDesc(),
                    FeeStatusEnum.CS_SUCCESS.getDesc(), "审核成功（备注内容："+chargeFeeManage.getRemark()+")", chargeFeeManage.getUpdateName());
        }else{
            commonService.insetLogger(feeManage.getServiceNo(),
                    ChargeLogEnum.LOG_CHARGE_ORDER_APPLY.getDesc(),
                    "费用审核操作",
                    FeeStatusEnum.CS_REFUSE.getDesc(),
                    FeeStatusEnum.CS_REFUSE.getDesc(), "审核失败（备注内容："+chargeFeeManage.getRemark()+")", chargeFeeManage.getUpdateName());
        }

        return jdbcSession.updateById(feeManage);
    }


    @Override
    public Object deleteById(String id) {
        return null;
    }


    @Override
    public Object addApplyFee(ChargeFeeManage feeManage) {

        //查看是否需要审核
        List<ChargeFeeConfig> feeConfigs = jdbcSession.findArray(ChargeFeeConfig.class)
                .eq("communityNo",feeManage.getCommunityNo()).exe();

        //默认
        feeManage.setApplyStatus(FeeStatusEnum.CS_SUCCESS);

        if(Objects.nonEmpty(feeConfigs)){
            ChargeFeeConfig config = feeConfigs.get(0);
            feeManage.setCommunityName(config.getCommunityName());
            feeManage.setApplyName(config.getApplyName());
            feeManage.setApplyUserNo(config.getApplyUserNo());
            feeManage.setApplyStatus(FeeStatusEnum.CS_UN_TREATED);
        }

        //添加减免费用
        feeManage.setStatus(true);
        String serviceNo = CommonUtil.generateRandom("FC");
        feeManage.setServiceNo(serviceNo);
        jdbcSession.insert(feeManage);

        return Result.success(serviceNo);
    }

    @Override
    public Object getObj(JSONObject jsonObject) {
        return jdbcSession.findOne(ChargeFeeManage.class)
                .eq(jsonObject,"serviceNo").exe();
    }

    @Override
    public Object eumState() {
        HashMap<String, String> map = ChargeStatusEnum.getMap();
        return map;
    }


}
